# -*- coding:utf-8 -*-
# @FileName  :utils.py
# @Time      :2020/10/25 14:59
# @Author    :zhoujirong
import redis
import time
import hmac
import base64
import hashlib
import os
from urllib.parse import quote
from common.config_parse import parse_ini
from common.operate_db import MySQL
from common.operate_db import MyOracle
from conf.settings import DOWNLOAD_DATA_PATH
from common.log import Log

ddconfig = parse_ini('dingding') #取钉钉的配置信息
secret = ddconfig.get("secret")


mysql_conn_mapper = {} #{mysqlNone:Mysql,mysql2None:Mysql2}
def get_mysql(node='mysql',db=None):#使用数据库类型 mysql
    key = '%s%s'%(node,db) #mysql2None
    if not key in mysql_conn_mapper:
        mysql_info = parse_ini(node)
        if db:
            mysql_info['db'] = db
        if node == 'mysql':
            mysql = MySQL(**mysql_info)
            mysql_conn_mapper[key] = mysql
        if node == 'oracle':
            mysql = MyOracle(**mysql_info)
            mysql_conn_mapper[key] = mysql
    else:
        mysql =  mysql_conn_mapper[key]
    return mysql

#弃用
# myoracle_conn_mapper = {} #{mysqlNone:Mysql,mysql2None:Mysql2}
# def get_oracle(node='oracle',db=None):#使用数据库类型 oracle
#     key = '%s%s'%(node,db) #mysql2None
#     if not key in myoracle_conn_mapper:
#         myoracle_info = parse_ini(node)
#         if db:
#             myoracle_info['db'] = db
#         mysql = MyOracle(**myoracle_info)
#         myoracle_conn_mapper[key] = mysql
#     else:
#         mysql =  myoracle_conn_mapper[key]
#     return mysql


redis_mapper = {}
def get_redis(node='redis',db=None):
    key = '%s%s'%(node,db) #mysql2None
    if not key in redis_mapper:
        redis_info = parse_ini(node)
        if db:
            redis_info['db'] = db
        r = redis.Redis(**redis_info,decode_responses=True)
        redis_mapper[key] = r
    else:
        r = redis_mapper[key]
    return r

def create_sign():
    timestamp = int(time.time() * 1000)
    sign_before  = '%s\n%s' % (timestamp,secret)
    hsha265 = hmac.new(secret.encode(),sign_before.encode(),hashlib.sha256)
    sign_sha256 = hsha265.digest()
    sign_b64 = base64.b64encode(sign_sha256)
    sign = quote(sign_b64)
    return {"timestamp":timestamp,"sign":sign}

def download(file_name,content):
    file_path = os.path.join(DOWNLOAD_DATA_PATH,file_name)
    with open(file_path,'wb') as f:
        f.write(content)
        Log.info('【%s】已下载/导出/保存完成！'%file_name)
    file_size = os.path.getsize(file_path)
    return file_size




if __name__ == "__main__":
    # c = get_redis()
    # print(c.hgetall('org_jurisdiction_key'))
    c = get_mysql('oracle')
    print(c)
    b = c.fetchall('select * from cpq_config')
    print(b)


